import * as comm from '../../../utils/common';
const storageService = require('../../../services/storage')

// 获取 App 实例
const appInstance = getApp();
Component({
  properties: {
    device: {
      type: Object,
      value: {
        deviceId: null,
        totalSwitch: false,
        name: '设备名称',
        status: '当前行程',
        power: false,
        startTime: '--:--',
        endTime: '--:--',
        temperature: '30',
        //bluetoothStatus: '00', // 蓝牙状态：00-未连接，01-已连接，04-连接中，05-连接错误
        //wifiStatus: '02', // WiFi状态：02-未连接，03-已连接，06-连接中，07-连接错误
        fanStatus: '06', // 风扇状态：06-未启动，07-已启动
        online: 0,
        topicSend: '',
        topicSub: '',
      },
    },
    index: {
      type: Number,
      value: 0,
    },
    disableNavigation: {
      type: Boolean,
      value: false
    },
  },

  data: {
    longPressThreshold: 3000, // 长按阈值3秒
    getValInterval: null,
    channels: [],
    lastTapTime: 0,
    lastTapTimestamp: 0, // 用于记录上一次点击的时间戳
    singleTapTimer: null,
  },

  lifetimes: {
    attached() {
      console.log("attached...")
      const $t = this;
      let arr = storageService.getDeviceChannels(this.data.device.deviceId)
      this.setData({
        channels: arr
      })

      $t.data.getValInterval = setInterval(() => {
        $t.getVal()
      }, 10000);
      $t.getVal(1);
    },

    detached() {
      console.log("detached...")
      clearTimeout(this.data.getValInterval);
      this.data.getValInterval = null;
      clearTimeout(this.data.singleTapTimer);
      this.data.singleTapTimer = null;
    }
  },

  methods: {
    initVal(obj) {
      let valArr = obj.msg.split(';');
      for (var i = 0; i < this.data.channels.length; i++) {
        if (valArr.length > i) {
          this.data.channels[i].v = parseInt(valArr[i]);
          this.data.channels[i].barv = this.data.channels[i].v > 5 ? this.data.channels[i].v : 5;
        }
      }
      this.setData({
        channels: this.data.channels
      })
    },
    getVal(flagInit) {
      if (flagInit == 1 || this.data.device.online == 1) {
        appInstance.sendMtMsg(this.data.device.topicSend, "getVal", null);
      }
    },


    // 切换总开关状态
    toggleSwitch(e) {
      const currentTime = e.timeStamp;
      const timeDiff = currentTime - this.data.lastTapTime;

      if (timeDiff > 0 && timeDiff < 300) {
        // 双击事件
        this.doubleTapAction(e);
        this.setData({
          lastTapTime: 0
        }); // 重置，防止三击误判
      } else {
        // 第一次点击或超时，记录时间并设置定时器等待第二次点击
        this.setData({
          lastTapTime: currentTime
        });

        // 延迟执行单击操作，若在延迟期内有第二次点击则取消单击
        this.data.singleTapTimer = setTimeout(() => {
          if (this.data.lastTapTime === currentTime) { // 确保仍是第一次点击的记录
            this.singleTapAction(e); // 执行单击逻辑
          }
        }, 300);
      }
    },

    /*
    // 切换设备电源状态
    togglePower() {
      const power = !this.data.device.power
      const index = this.data.index

      // 导入storage服务
      const storageService = require('../../../services/storage')

      // 更新本地存储中的设备状态
      const devices = storageService.getDevices() || []
      devices[index].power = power
      storageService.saveDevices(devices)

      this.setData({
        'device.power': power,
      })
    },
    */

    // 长按设备卡片处理（删除设备）
    handleLongPress(e) {
      if (e.target.dataset.type === 'name' || e.target.dataset.type === 'power') {
        return
      }
      wx.showModal({
        title: '删除设备',
        content: '确定要删除此设备吗？',
        success: res => {
          if (res.confirm) {
            this.triggerEvent('deleteDevice', {
              index: this.data.index
            })
          }
        },
      })
    },

    // 长按设备名称处理（修改名称）
    handleNameLongPress(e) {
      if (e && e.stopPropagation) {
        e.stopPropagation()
      }
      wx.showModal({
        title: '修改设备名称',
        content: '',
        editable: true,
        placeholderText: '请输入新的设备名称',
        success: res => {
          if (res.confirm && res.content) {
            const index = this.data.index
            // 触发nameChange事件，通知父组件名称已更改
            this.triggerEvent('nameChange', {
              index: index,
              name: res.content,
            })
          }
        },
      })
    },

    // 点击设备卡片跳转到模式设置页面R
    navigateToModeSetting(e) {

      if (e.target.dataset.type === 'total' || e.target.dataset.type === 'name' || e.target.dataset.type === 'device-info') {
        return
      }
      let url=`/packageSeahwaterDiy/pages/mode_setting/mode_setting?did=${this.data.device.deviceId}`
      wx.navigateTo({
        url: url,
      })
    },

    // 点击设备信息按钮跳转到设备信息页面
    navigateToDeviceInfo(e) {
      // 已使用catchtap绑定事件，无需手动阻止冒泡
      wx.navigateTo({
        url: `/packageSeahwaterDiy/pages/device_info/device_info?did=${this.data.device.deviceId}`,
      })
    },
    singleTapAction(e) {
      const type = e.currentTarget.dataset.type
      const newValue = !this.data.device.totalSwitch
      if (this.data.device.online != 1) {
        wx.showToast({
          title: '设备不在线，操作失败!',
          icon: 'none',
        })
        return
      }
      this.triggerEvent('switchchange', {
        type,
        value: newValue,
        index: this.data.index,
      })
    },
    doubleTapAction(e) {
      clearTimeout(this.data.singleTapTimer); // 清除可能存在的单击定时器
      const type = e.currentTarget.dataset.type
      const newValue = !this.data.device.totalSwitch
      if (this.data.device.online != 1) {
        wx.showToast({
          title: '设备不在线，操作失败!',
          icon: 'none',
        })
        return
      }
      this.triggerEvent('switchDbchange', {
        type,
        value: newValue,
        index: this.data.index,
      })
    },




  },



})